import threading, thread, time
import gobject, gtk

gtk.gdk.threads_init()

class Pygtk_Thread(object):
   def __init__(self, update_function, complete_callback,complete_callback_args=None):
       self.update_function = update_function
       self.complete_callback = complete_callback
       self.complete_callback_args = complete_callback_args
       
   def _start(self,*args):
       self._stopped = False
       self.update_function(*args)
       if self._stopped:
           thread.exit()
       if self.complete_callback_args is not None:
           gobject.idle_add(self.complete_callback,self.complete_callback_args)
       else:
           gobject.idle_add(self.complete_callback)
   
   def start(self, *args):
       threading.Thread(target=self._start, args=args).start()

   def stop(self):
       self._stopped = True

if __name__ == '__main__':
    class MainWindow(gtk.Window):
       def __init__(self):
           super(MainWindow, self).__init__()
           self.location = None
           self.locations = sysaccess.load()
           vb = gtk.VBox()
           self.add(vb)
           self.Lbl_current_location = gtk.Label("unknow")
           vb.pack_start(self.Lbl_current_location)
           b = gtk.Button("Refresh")
           vb.pack_start(b)
           b.connect('clicked', self.on_button_clicked)
           self.show_all()
    
       def on_button_clicked(self, button):
           Pygtk_Thread(self.get_current_location,
                         self.update_current_location).start()
    
       def get_current_location(self):
           self.ip = sysaccess.get_net_ip()
           for location in self.locations:
               if self.locations[location].domain != None:
                   if self.locations[location].domain == self.ip:
                       self.location = self.locations[location].name
    
       def update_current_location(self):
           if self.location != None:
               self.Lbl_current_location.set_text(self.location + " " +self.ip)
           else :
               self.Lbl_current_location.set_text("unknow")
    
    import sysaccess
    w = MainWindow()
    gtk.main()